//    Copyright (c) 2009 Elwyn Malethan
//
//    This file is part of SeemoreJ.
//
//    SeemoreJ is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    SeemoreJ is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with SeemoreJ.  If not, see <http://www.gnu.org/licenses/>.

package com.malethan.seemorej.hibernate;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * <p>This is filter to open a hibernate seesion prior to a page loading and to close it after the page has loaded.
 *  This allows to have lazily initialised collections etc.</p>
 */
public class HibernateSessionFilter extends OncePerRequestFilter
{
    //----------------------------------------------------------------------- Static Properties and Constants

    private static final Log log = LogFactory.getLog(HibernateSessionFilter.class);

    //----------------------------------------------------------------------- Static Methods
    //----------------------------------------------------------------------- Instance Properties
    //----------------------------------------------------------------------- Constructors
    //----------------------------------------------------------------------- Getters and Setters
    //----------------------------------------------------------------------- Instance Methods

    public void doFilterInternal(HttpServletRequest servletRequest, HttpServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
    {
        //open hibernate session and make available via the thread
        HibernateUtil.registerInterceptor(new TimestampInterceptor());
        HibernateUtil.openSession();

        try
        {
            //run the page
            filterChain.doFilter(servletRequest, servletResponse);
        }
        catch (Exception e)
        {
            String errMsg = "An exception was thrown in the application which would have prevented the DB connection from being closed";
            log.error(errMsg, e);
            throw new ServletException(errMsg, e);
        }
        finally
        {
            //close the hibernate session we're using
            HibernateUtil.closeSession();
        }
    }
}
